<template>
  <el-container id="rootBox" ref="rootBox" class="rootBox">
    <el-tabs v-model="activeName"  style="width: 100%"  :stretch="true" @tab-click="handleClick" >
      <el-tab-pane label="数据库删除备份库" name="0">
        <el-row>
          <el-col :span="24" >
            <el-form :inline="true" :model="formInline" size="medium " >
              <el-form-item label="删除起止日期" required>
                <el-date-picker
                  :format="dates.defaultDatePattern"
                  v-model="formInline.deleteBeginEnd"
                  type="daterange"
                  popper-class="el-date-range-picker-left320"
                  ref="deleteBeginEnd"
                  align="right"
                  unlink-panels
                  range-separator="至"
                  @change="deleteBeginEndChange"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  :picker-options="dates.pickerOptions.timeInterval">
                </el-date-picker>
              </el-form-item>
              <el-form-item label="备份表" required>
                <el-select ref="tableName" v-model="formInline.tableName" @change="tableNameChange" placeholder="请选择"   >
                  <el-option :label="dvdeleteDbTable" :value="dvdeleteDbTable" v-for="(dvdeleteDbTable,index) in Object.keys(dvdeleteDbTables)" :key="index"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="模糊查询" >
                <el-input v-model="formInline.searchKey" placeholder="所有字段"  clearable @keyup.native.enter="query"/>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="query" >查询</el-button>
              </el-form-item>
            </el-form>
          </el-col>
        </el-row>
        <el-row v-if="tableColumns.length > 0">
          <el-col :span="24" >
            <el-button type="primary" @click="copyInsert">复制sql</el-button>
          </el-col>
          <el-col :span="24" >
            <el-table
              :data="tableDatas"
              ref="table"
              stripe
              border
              :height="winHeight"
              size="small"
              empty-textr="没有相关数据"
              @selection-change="handleSelectionChange"
              style="width: 100%">
              <el-table-column
                type="selection"
                width="55">
              </el-table-column>
              <el-table-column
                align="center"
                fixed="left"
                type="index" >
              </el-table-column>

              <el-table-column
                v-for="(tableColumn,index) in tableColumns" :key="index"
                :prop="tableColumn.columnname"
                :label="strings.defaultIfBlank(tableColumn.columncomment,tableColumn.columnname)"
                :fixed="['delete_date','delete_user','id','bus_key'].includes(tableColumn.columnname) ? 'left' : null"
                show-overflow-tooltip
                sortable
                :width="getColumnWidth(tableColumn)"
              >
              </el-table-column>

              <el-table-column
                label="操作"
                fixed="right"
                width="100">
                <template slot-scope="scope">
                  <el-button size="mini" type="primary"  @click="copyInsert(scope.row, true)" >复制sql</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-col>
        </el-row>
      </el-tab-pane>

      <el-tab-pane label="数据库备份记录" name="1">
        <FortenVxetableStatic :data="dbbackData" :columns="dbbackTableColumns" :maxHeight="maxHeight" :btnList="dbbackBtnList" @userFun="userFun" pkName="name"
                              :searchFieldArr="['name']"
                              searchPlaceholder="搜索文件名"
                              :defaultSort="dbbackDefaultSort"
                              :buttonList="dbbackButtonList"
        ></FortenVxetableStatic>
      </el-tab-pane>
    </el-tabs>
  </el-container>
</template>

<script>
import FortenVxetableStatic from '@/components/common/FortenVxetableStatic.vue'
/*eslint-disable*/
export default {
  name: 'rootBox',
  components: {
    FortenVxetableStatic
  },
  data() {
    return {
      activeName: '0',
      formInline: {},
      dvdeleteDbTables: [],
      dvdeleteTabledDate: [],
      tableColumns: [],
      tableDatas: [],
      winHeight: window.innerHeight - 300,
      tableCheckList: [],
      tableNameSelect: '',

      dbbackData: [],
      dbbackTableColumns: [
        {field: 'lastModified', title: '文件生成时间',width: 140,  titleHelp: '文件生成时间', sortable: true,},

        {field: 'name', title: '文件名', width: 150, fixed: 'left', titleHelp: '文件名', sortable: true,},
        {field: 'size', title: '文件大小(M：兆)', width: 120, titleHelp: '文件大小', sortable: true,},
        {field: 'path', title: '文件路径', titleHelp: '文件路径'},

      ],

      //按钮列表
      dbbackBtnList: [{
        key: 'download',
        icon: 'el-icon-download',
        size: 'mini',
        type: 'primary',
        style: {padding: '6px'},
        title: '下载该备份文件'
      }],

      //按钮列表
      dbbackButtonList: [{
        key: 'load',
        type: 'primary',
        title: '刷新数据',
        text: '刷新'
      }],

      //默认排序
      dbbackDefaultSort: {
        field: 'lastModified',
        order: 'desc',
      },
      maxHeight: window.innerHeight - 200,
    }
  },
  methods: {
    query() {
      if (this.strings.isBlank(this.formInline.tableName)) {
        this.utilMessage.warning('请选择需要查询的表')
        this.$refs.tableName.focus()
        return
      }

      if (this.strings.isBlank(this.formInline.deleteBeginEnd)) {
        this.utilMessage.warning('请选择删除起止日期')
        this.$refs.deleteBeginEnd.focus()
        return
      }

      this.utilVue.loadShow(true)
      let searchKey = this.strings.defaultIfBlank(this.formInline.searchKey, '')

      this.tableDatas = []
      let param ={
        tableName:  this.formInline.tableName,
        deleteBegin:  this.formInline.deleteBegin,
        deleteEnd:  this.formInline.deleteEnd,
        searchKey:  searchKey
      }

      this.$ajax.post(`/sys/database/getDvdeleteTableData`, param).then(resp => {
        if (resp.code == 0 && resp.data) {
          this.tableDatas = resp.data
        }
        this.utilVue.loadHide()
      })

    },
    getDvdeleteDbTables() {
      this.utilVue.loadShow(true)
      this.$ajax.get(`/sys/database/getDvdeleteDbTables`).then(resp => {
        if (resp.code == 0 && resp.data) {
          this.dvdeleteDbTables = resp.data
        }

        this.utilVue.loadHide()
      })
    },

    //日期选择后
    deleteBeginEndChange() {
      this.$set(this.formInline, 'deleteBegin',this.dates.formatToAnotherPattern(this.formInline.deleteBeginEnd[0],'yyyy-MM-dd')  )
      this.$set(this.formInline, 'deleteEnd', this.dates.formatToAnotherPattern(this.formInline.deleteBeginEnd[1],'yyyy-MM-dd')+' 23:59:59')
      this.query()
    },
    //表选择后
    tableNameChange(tableName) {

      this.tableNameSelect = tableName
      this.tableColumns = []
      setTimeout(() => {
        this.tableColumns = this.dvdeleteDbTables[tableName]
      }, 500)

      this.query()
    },

    getColumnWidth(tableColumn) {
      if ( ['date','datetime'].includes(tableColumn.datatype)) return 140
      if (tableColumn.columnname.indexOf('user') != -1) return 90
      if (tableColumn.columnname.indexOf('amount') != -1 || tableColumn.columnname.indexOf('qty') != -1) return 100
      return 150
    },

    copyInsert(dataRow, isRow) {

      let tableCheckListNew = this.tableCheckList
      if (isRow == true) {
        tableCheckListNew = [dataRow]
      }

      if (!tableCheckListNew || tableCheckListNew.length < 1) {
        this.utilMessage.error('请先选中需要复制的记录')
        return
      }

      let insertSqlArr = []
      tableCheckListNew.forEach(data => {
        let nameArr =[]
        let valueArr =[]
        Object.keys(data).forEach(key => {
          if (['delete_date','delete_user'].includes(key)) return true
          nameArr.push("`"+key+"`")
          let value = data[key]
          if (this.strings.isBlank(value)) {
            valueArr.push(null)
          }else {
            valueArr.push("'"+value+"'")
          }
        })
        insertSqlArr.push(' insert into '+this.tableNameSelect.replace('_dvdelete','')+' ('+nameArr.join(',')+') values ('+this.strings.joinWithNull(valueArr,',')+');\n')
      })

      let msg = `
<textarea rows="3" cols="20" style="height: 400px; width: 100%; font-size: 13px; line-height: 13px;border-color: #3a8ee6; outline: none; resize: none;    white-space: nowrap;">
${insertSqlArr.join('')}
</textarea>
`
      global.utilMessage.alertFail(msg, '正式表的insert语句为', {
        confirmButtonText: '确定',
        dangerouslyUseHTMLString: true,
        callback: action => {
        }
      });

    },
    handleSelectionChange(val) {
      this.tableCheckList = val
    },

    //标签点击
    handleClick(tab) {
      if (tab.name == '1' ){
        this.getDbbackData()
      }
    },

    //获取备份列表
    getDbbackData(isUserOp){
      if (isUserOp == true) {
        this.utilVue.loadShow(true)
      }
      this.dbbackData=[]
      this.$ajax.get(`/sys/log/getDbbackData`).then(response => {
        if (response.code == 0) {
          this.dbbackData = response.data
          if (isUserOp == true) this.utilVue.loadHide()
        }
      })
    },


    //回调函数
    userFun({config, scope}) {

      switch (config.key) {
        case 'download': //下载
          this.utils.downloadAbfile(scope.row.path, scope.row.name)
          break
        case 'load': //刷新
          this.getDbbackData(true)
          break
      }
    },
  },
  mounted() {
    this.getDvdeleteDbTables()
  },
  comments: {
  },
  computed:{
  }
}
</script>

<style lang="scss" scoped>
.rootBox{
  padding:  0px 11px;

  /deep/ .el-table{
    th{
      .cell{
        white-space: nowrap !important;
      }
    }
  }
}
</style>
